import { inject, injectable } from 'inversify';
import { APIClient, HttpMethod } from '@todo/core';
import { EAuthEndpoints } from '../config/endpoints.ts';
import { requestLoginDTO, responseLoginDTO } from './auth.dto.ts';

@injectable()
export class AuthRepository {
  constructor(
    @inject(APIClient)
    private apiClient: APIClient,
  ) {}

  async login(login: string, password: string): Promise<responseLoginDTO> {
    return await this.apiClient.request<requestLoginDTO, responseLoginDTO>({
      route: EAuthEndpoints.LOGIN,
      method: HttpMethod.POST,
      requestObj: {
        email: login,
        password,
        adminLogin: true,
      },
    });
  }

  async refresh(): Promise<responseLoginDTO> {
    if (!this.apiClient.refreshToken) {
      return Promise.reject();
    }
    return await this.apiClient.request<requestLoginDTO, responseLoginDTO>({
      route: EAuthEndpoints.REFRESH,
      method: HttpMethod.POST,
      headers: {
        Authorization: `Bearer ${this.apiClient.refreshToken}`,
      },
      widthCredentials: false,
    });
  }
}
